//
//  YJMainTabBar.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/10.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import UIKit

let TabBarItemCount = 5

class YJMainTabBar: UITabBar {
    // 闭包属性
    var composeButtonCallback: (()->())?
    

    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 宽度
        let width = frame.width / CGFloat(TabBarItemCount)
        // 计算最左边的这个frame,后面使用CGRectOffset
        let originFrame = CGRect(x: 0, y: 0, width: width, height: frame.height)
        
        var index = 0
        for subview in subviews {
            let cls = NSClassFromString("UITabBarButton")
//            guard let cls = try? NSClassFromString("UITabBarButton") else {
//                print("没有该类!!!")
//                return
//            }
            if subview.isKind(of: cls!) {
                subview.frame = originFrame.offsetBy(dx: width * CGFloat(index), dy: 0)
                index += index == 1 ? 2 : 1
            }
        }
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.height)
    }
    
    // MARK: - 按钮点击事件
    func didClickComposeButton() -> Void {
        // 执行闭包
        composeButtonCallback?()
    }
    
    private lazy var composeButton: UIButton = {
        let button = UIButton(type: UIButtonType.custom)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState())
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        
        button.addTarget(self, action: #selector(didClickComposeButton), for: .touchUpInside)
        
        self.addSubview(button)
        
        return button
    }()

}
